package com.wuyi.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wuyi.mapper.*;
import com.wuyi.pojo.*;
import com.wuyi.pojo.bo.CenterUserInfoBO;
import com.wuyi.pojo.bo.UserPwdBO;
import com.wuyi.pojo.vo.CenterUserInfoVO;
import com.wuyi.pojo.vo.ResourceVO;
import com.wuyi.service.CenterUserService;
import com.wuyi.service.FileUploadService;
import com.zc.utils.JSONResult;
import com.zc.utils.MD5Utils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 曾川
 * @version 1.0.0
 * @ClassName CenterUserServiceImpl.java
 * @Description 个人管理Service实现类
 * @createTime 2021年11月09日 20:52:00
 */
@Service
public class CenterUserServiceImpl implements CenterUserService {

    final static Logger logger = LoggerFactory.getLogger(CenterUserServiceImpl.class);
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private FollowMapper followMapper;
    @Autowired
    private PostMapper postMapper;
    @Autowired
    private ResourceMapper resourceMapper;
    @Autowired
    private CollectMapper collectMapper;
    @Autowired
    private CollectMapperCustom collectMapperCustom;
    @Autowired
    private ResourceCustomerMapper resourceCustomerMapper;

    @Autowired
    private FileUploadService fileUploadService;




    @Transactional( propagation = Propagation.SUPPORTS)
    @Override
    public CenterUserInfoVO queryUserInfo(String userId) {

        CenterUserInfoVO userInfoVO = new CenterUserInfoVO();

        //1.先查询个人信息
        User user = new User();
        user.setUserId(userId);
        User user1 = userMapper.selectOne(user);
        BeanUtils.copyProperties(user1, userInfoVO);
        userInfoVO.setUserRole(user1.getUserRole());

        //2.计算个人发起帖子数   个人粉丝数   个人关注数
        Post post = new Post();
        post.setPostUid(user1.getUserName());
        int postNum = postMapper.selectCount(post);
        userInfoVO.setPostNum(postNum);

        //计算粉丝数
        Follow follow = new Follow();
        follow.setFollowedUid(user1.getUserName());
        int fansNum = followMapper.selectCount(follow);
        userInfoVO.setFansNum(fansNum);
        //计算关注数
        Follow follow2 = new Follow();
        follow2.setFollowUid(user1.getUserName());
        int followNum = followMapper.selectCount(follow2);
        userInfoVO.setFollowNum(followNum);
        //3.收藏的记录数  资料上传的记录数
        Map<String, Object> map = new HashMap<>();
        map.put("userId", user1.getUserName());
        map.put("categoryId", 1);

        //收藏的记录数
        //计算收藏资料数
        int collectMatNum = collectMapperCustom.getMyCollectCounts(map);
        userInfoVO.setCollectMatNum(collectMatNum);
        //计算收藏课件数
        map.put("categoryId", 2);
        int collectCouNum = collectMapperCustom.getMyCollectCounts(map);
        userInfoVO.setCollectCouNum(collectCouNum);
        //计算收藏软件数
        map.put("categoryId", 3);
        int collectSofNum = collectMapperCustom.getMyCollectCounts(map);
        userInfoVO.setCollectSofNum(collectSofNum);

        //资料上传的记录数
        //计算上传资料数
        Resource resource = new Resource();
        resource.setResourceUid(user1.getUserName());
        resource.setResourceCid(1);
        int resourceMatNum = resourceMapper.selectCount(resource);
        userInfoVO.setResourceMatNum(resourceMatNum);
        //计算上传课件数
        resource.setResourceCid(2);
        int resourceCouNum = resourceMapper.selectCount(resource);
        userInfoVO.setResourceCouNum(resourceCouNum);
        //计算上传软件数
        resource.setResourceCid(3);
        int resourceSofNum = resourceMapper.selectCount(resource);
        userInfoVO.setResourceSofNum(resourceSofNum);

        return userInfoVO;
    }

    /**
     * 修改个人信息
     *
     * @param userInfoBO
     * @return
     */
    @Transactional( propagation = Propagation.REQUIRED)
    @Override
    public void updateUserInfo(CenterUserInfoBO userInfoBO) {

        User user = new User();
        BeanUtils.copyProperties(userInfoBO, user);
        user.setUserId(userInfoBO.getUserId());
        user.setUpdateTime(new Date());
        userMapper.updateByPrimaryKeySelective(user);
    }

    /**
     * 修改头像
     *
     * @param userId
     * @param images
     */
    @Transactional( propagation = Propagation.REQUIRED)
    @Override
    public JSONResult updateUserFace(String userId, MultipartFile images) throws IOException {


        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId", userId);
        User user = userMapper.selectOneByExample(example);
        if (null != user) {
            String userFacePath = fileUploadService.upload(images, user.getUserName(), "userFace");
            logger.info("userFacePath =======" + userFacePath);
            user.setUserFace(userFacePath);
            int i = userMapper.updateByPrimaryKey(user);
            if (i != 1) {
                return JSONResult.errorMsg("更新头像失败");
            }
        }
        return JSONResult.ok("更新头像成功");


    }

    /**
     * 用户修改密码
     *
     * @param psdBO
     */
    @Transactional( propagation = Propagation.REQUIRED)
    @Override
    public JSONResult changePsd(UserPwdBO psdBO) throws Exception {
        //先查询原密码是否一样
        Example example = new Example(User.class);
        example.createCriteria().andEqualTo("userId", psdBO.getUserId());
        User user = userMapper.selectOneByExample(example);
        if (!user.getUserPassword().equals(MD5Utils.getMD5Str(psdBO.getOldPwd()))) {
            return JSONResult.errorMsg("与原密码不符");
        }
        //再进行修改
        user.setUserPassword(MD5Utils.getMD5Str(psdBO.getNewPwd()));
        user.setUpdateTime(new Date());
        int i = userMapper.updateByPrimaryKeySelective(user);
        if (i != 1) {
            return JSONResult.errorMsg("修改密码失败");
        }
        return JSONResult.ok("修改密码成功");
    }

    /**
     * 查询个人收藏资源
     *
     * @param categoryId
     * @param userName
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Transactional( propagation = Propagation.SUPPORTS)
    @Override
    public PageInfo myColList(Integer categoryId, String userName, Integer pageNum, Integer pageSize) {

        PageHelper.startPage(pageNum,pageSize);
        //查询个人收藏的资源
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userName);
        map.put("categoryId", categoryId);
        List<ResourceVO> resourceVOList = resourceCustomerMapper.queryMyColResList(map);

        //先将数据全部查询出来
        List<Collect> collectList = collectMapper.selectAll();
        List<Follow> followList = followMapper.selectAll();
        //遍历set值
        for (ResourceVO resourceVO : resourceVOList) {
            //默认为0
            resourceVO.setIsFollowed(0);
            resourceVO.setIsCollected(0);
            //判断收藏表，与当前登录的用户判断
            for (Collect collect : collectList) {
                //若收藏表中的userName与当前登录用户的userName一致
                //且收藏表中的资源ID与vo里的资源ID一致，则表示已收藏
                if (collect.getCollectUid().equals(userName) &&
                        resourceVO.getResourceId().equals(collect.getCollectRid())) {
                    resourceVO.setIsCollected(1);
                }
            }
            //判断关注表，与当前登录的用户判断
            for (Follow follow : followList) {
                //若关注表中的userName与当前登录用户的userName一致
                //且关注表中的被关注人userName与vo里的userName一致，则表示已关注
                if (follow.getFollowUid().equals(userName) &&
                        resourceVO.getResourceUserName()
                                .equals(follow.getFollowedUid())) {
                    resourceVO.setIsFollowed(1);
                }
            }
        }
        PageInfo pageInfo = new PageInfo<>(resourceVOList);
        pageInfo.setList(resourceVOList);
        return pageInfo;
    }

    /**
     * 帖子管理模块---查询帖子个人列表
     * @param userName
     * @param postTitle
     * @param postTime
     * @param pageNum
     * @param pageSize
     * @return
     * @throws ParseException
     */
    @Transactional( propagation = Propagation.SUPPORTS)
    @Override
    public PageInfo queryUserPostInfo(String userName,
                                      String postTitle,
                                      String postTime,
                                      Integer pageNum,
                                      Integer pageSize) throws ParseException {

        PageHelper.startPage(pageNum,pageSize);
        Example example = new Example(Post.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("postUid", userName);
        if (StringUtils.isNotBlank(postTitle)) {
            criteria.andLike("postTitle","%" + postTitle + "%");
        }

        if (StringUtils.isNotBlank(postTime)) {

            logger.info(postTime.substring(1, postTime.length() - 1));

            DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
            Date date = format1.parse(postTime.substring(1, postTime.length() - 1));
            criteria.andEqualTo("postTime", date);
        }
        example.orderBy("createTime").desc();

        List<Post> posts = postMapper.selectByExample(example);
        PageInfo pageInfo = new PageInfo<>(posts);
        pageInfo.setList(posts);

        return pageInfo;
    }
}
